<template>
  <div class="w">
    <!-- 登录模块区域 -->
    <div class="login">
      <!-- 登录左侧图片区域 -->
      <div class="login-left">
        <img src="../../img/login_bg_pic.jpg" alt="" />
      </div>

      <!-- 登录右侧区域 -->
      <div class="login-right">
        <!-- 右侧logo区域 -->
        <div class="logo">
          <img src="../../img/logo.png" alt="" />
        </div>

        <!-- 右侧表单区域 -->
        <div class="info">
          <el-form ref="loginRef" :model="loginForm" label-width="80px" :rules="loginRules">
            <el-form-item label="用户名" prop="userName" v-if="!loginMode">
              <el-input
                v-model="loginForm.userName"
                clearable
                placeholder="请输入用户名"
                style="width: 260px"
                prefix-icon="iconfont icon-denglu"
              ></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone" v-if="loginMode">
              <el-input
                v-model="loginForm.phone"
                clearable
                placeholder="请输入手机号"
                style="width: 260px"
                prefix-icon="iconfont icon-denglu"
              ></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" v-if="!loginMode">
              <el-input
                v-model="loginForm.password"
                placeholder="请输入密码"
                style="width: 260px"
                clearable=""
                type="password"
                prefix-icon="iconfont icon-tianchongxing-"
              ></el-input>
            </el-form-item>
            <el-form-item label="验证码" prop="code" v-if="loginMode" class="code">
              <el-row :gutter="5">
                <el-col>
                  <el-input
                    v-model="loginForm.code"
                    placeholder="请输入验证码"
                    style="width: 180px"
                    clearable=""
                    prefix-icon="iconfont icon-tianchongxing-"
                  >
                  </el-input>
                </el-col>
                <el-col>
                  <el-button type="primary" size="mini" style="width: 75px" @click="sendCode">发送验证码</el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
        </div>

        <!-- 右侧提示区域 -->
        <div class="notic">
          <el-button @click="loginPhone" v-if="!loginMode" type="text" style="font-size: 12px; color: #334353">手机验证码登录</el-button>
          <el-button @click="loginPhoneBack" v-if="loginMode" type="text" style="font-size: 12px; color: #334353">密码登录</el-button>
          <el-button @click="losePassword" type="text" style="font-size: 12px; color: #334353">忘记密码？</el-button>
        </div>

        <!-- 登录按钮区域 -->
        <div class="button" v-if="!loginMode">
          <el-button type="primary" style="width: 150px" @click="login" :loading="loading">
            <span v-if="!loading">登录</span>
            <span v-else>加载中</span></el-button
          >
        </div>
        <div class="button" v-if="loginMode">
          <el-button type="primary" style="width: 150px" @click="loginWithCode" :loading="loading">
            <span v-if="!loading">登录</span>
            <span v-else>加载中</span></el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    // 校验密码规则
    var checkPassword = (rule, value, cb) => {
      // 必须包含字母、数字、下划线的密码验证规则
      const regPassword = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{8,}$/;

      if (regPassword.test(value)) {
        return cb();
      }
      cb(new Error('密码必须包含数字、字母、特殊符号'));
    };

    // 手机号验证规则
    var checkPhone = (rule, value, cb) => {
      const regPhone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (regPhone.test(value)) {
        return cb();
      }
      cb(new Error('手机号不合法'));
    };
    return {
      loginForm: {
        // 密码登录输入框绑定的属性
        userName: '',
        password: '',

        // 验证码登录输入框绑定属性
        phone: '',
        code: '',
      },
      phoneCode: '',

      //密码和用户名校验的绑定属性
      loginRules: {
        //用户名验证规则
        userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],

        //密码验证规则
        password: [
          { validator: checkPassword, trigger: 'blur' },
          { required: true, message: '密码不能为空', trigger: 'blur' },
        ],

        // 手机验证规则
        phone: [
          { validator: checkPhone, trigger: 'blur' },
          { required: true, message: '手机号不能为空', trigger: 'blur' },
        ],

        // 验证码规则
        code: [
          { required: true, message: '验证码不能为空', trigger: 'blur' },
          { min: 4, max: 6, message: '长度在 4 到 6 个字符', trigger: 'blur' },
        ],
      },

      //用于切换登录按钮的状态
      loading: false,
      loginMode: false,
    };
  },

  methods: {
    // 密码登录
    login() {
      // 登录之前的预校验
      this.$refs.loginRef.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const { data: res } = await this.$http.post('login', this.loginForm);
          if (res.code == 1) {
            localStorage.setItem('userinfo', JSON.stringify(res.data));
            window.sessionStorage.setItem('token', res.data.token);
            window.location.href = '/user';
            this.$message.success('登陆成功');
          } else {
            this.$message.error(res.msg);
            this.loading = false;
          }
        } else {
          return this.$message.error('表单预校验失败 请检查数据格式是否输入正确');
        }
      });
    },

    // 验证码登录
    loginPhone() {
      this.loginMode = true;
      this.$refs.loginRef.resetFields();
    },
    loginPhoneBack() {
      this.loginMode = false;
      this.$refs.loginRef.resetFields();
    },

    // 忘记密码
    losePassword() {
      this.$router.push('/lose');
    },

    // 发送验证码
    async sendCode() {
      const { data: res } = await this.$http.post('loginWithPhone', { phone: this.loginForm.phone });
      console.log(res);
      if (res.code == 1) {
        this.$message.success(res.data);
      } else {
        this.$message.error(res.msg);
      }
    },

    // 比较严证码是否正确
    async loginWithCode() {
      this.$refs.loginRef.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const { data: res } = await this.$http.post('loginWithCode', { phone: this.loginForm.phone, code: this.loginForm.code });
          if (res.code == 1) {
            localStorage.setItem('userinfo', JSON.stringify(res.data));
            window.sessionStorage.setItem('token', res.data.token);
            window.location.href = '/';
            this.$message.success('登陆成功');
          } else {
            this.$message.error(res.msg);
            this.loading = false;
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.w {
  background: url('../../img/wallhaven-q2991r.png');
  background-size: cover;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  height: 100vh;

  .login {
    border-radius: 5px;
    display: flex;
    justify-content: space-between;
    width: 980px;
    height: 420px;

    .login-left {
      img {
        width: 610px;
        height: 420px;
        border-radius: 5px;
      }
    }
    .login-right {
      width: 370px;
      background-color: #fff;
      opacity: 0.9;
      border-radius: 5px;
      .logo {
        display: flex;
        align-items: center;
        justify-content: space-evenly;
        margin-top: 30px;
        margin-bottom: 50px;
        img {
          width: 250px;
        }
      }
      .info {
        .el-row {
          display: flex;
          align-items: center;
          justify-content: space-evenly;
          margin-bottom: 20px;
          .el-input {
            border: 0 0 1px 0;
          }
        }
      }
      .notic {
        display: flex;
        justify-content: space-between;
        font-size: 12px;
        margin: 0 25px 0 25px;
      }
      .button {
        display: flex;
        justify-content: space-evenly;
        margin-top: 30px;
      }
    }
  }
}
.send {
  display: flex;
  justify-content: space-evenly;
}
.el-button--mini,
.el-button--mini.is-round {
  padding: 8px 6px;
}
.code {
  margin-bottom: 0px;
}
</style>